import com.sun.deploy.ref.AppModel;

import java.util.Arrays;

public class Test {
    public static void main(String[] args) {
        int[] ret = {1, 9, 2, 8, 3, 7, 4, 6, 5};
        shellSort(ret);
        System.out.println(Arrays.toString(ret));
    }

    private static void shellSort(int[] array){
        int gap = array.length;
        while(gap>1){
             gap/=2;
             shell(array,gap);
        }
    }

    private static void shell(int[] array, int gap) {
        for (int i = gap; i < array.length; i++) {
            int tmp = array[i];
            int j = i-gap;
            for (; j >=0; j-=gap) {
                if(array[j]>tmp){
                    array[j+gap] = array[j];
                }else{
                    break;
                }
            }
            array[j+gap] = tmp;
        }
    }

    private static void insertSort(int[] array) {
        for (int i = 1; i < array.length; i++) {
            int tmp = array[i];
            int j = i-1;
            for (; j >=0; j--) {
                if(array[j]>tmp){
                    array[j+1] = array[j];
                }else{
                    break;
                }
            }
           array[j+1] = tmp;
        }
    }

    private static void selectSort(int[] array) {
        for (int i = 0; i < array.length; i++) {
            int minIndex = i;
            for (int j = i+1; j < array.length; j++) {
                if(array[j]<array[minIndex]){
                    minIndex = j;
                }
            }
            swap(array,minIndex,i);
        }
    }

    private static void bubbleSort(int[] array) {
        for (int i = 0; i < array.length-1; i++) {
            boolean flag = false;
            for (int j = 0; j < array.length-1-i; j++) {
                if(array[j]> array[j+1]){
                    swap(array,j,j+1);
                    flag = true;
                }
            }
            if(!flag)
                 return ;
        }
    }

    private static void heapSort(int[]  array) {
        for(int parent=(array.length-1-1)/2;parent>=0;parent--){
              siftDown(array,parent,array.length);
        }
        int end = array.length - 1;
        while(end>0){
            swap(array,0,end);
            siftDown(array,0,end);
            end--;
        }
    }

    private static void swap(int[] array, int a, int b) {
        int tmp = array[a];
        array[a] = array[b];
        array[b] = tmp;
    }

    private static void siftDown(int[] array, int parent, int end) {
        int child = 2 * parent + 1;
        while(child<end){
            if(child+1<end&&array[child+1]>array[child]){
                child++;
            }
            if(array[child]>array[parent]) {
                swap(array, child, parent);
                parent = child;
                child = 2 * parent + 1;
            }else {
                break;
            }
        }
    }

}
